#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：pythonProject2 
@File    ：server-new.py
@Author  ：beibei
@Date    ：2023/12/22 4:59 PM 
'''
import socket
import time

message_store = []

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ("127.0.0.1", 8991)
server_socket.bind(server_address)
server_socket.listen(1)
print('等待客户端连接')

while True:
    client_socket, client_address = server_socket.accept()
    print(f'Client connected: {client_address}')
    init_time = int(time.time())

    while True:
        if int(time.time()) - init_time > 5:
            break
        try:
            client_socket.settimeout(1)
            data = client_socket.recv(1024).decode('utf-8')
        except TimeoutError:
            continue
            print(f'data: {data}')

        if data == 'close':
            # 关闭连接
            client_socket.close()
            print('连接关闭')
            break
        elif data.startswith('push'):
            # 推送消息
            message = data.split('\n')[1].strip()
            message_store.append(message)
            response = '消息已成功推送'
            client_socket.sendall(response.encode('utf-8'))
        elif data == 'pull':
            # 拉取消息
            if message_store:
                messages = ', '.join(message_store)
                client_socket.sendall(messages.encode('utf-8'))
                message_store.clear()
            else:
                client_socket.sendall('当前没有消息可用'.encode('utf-8'))
        else:
            client_socket.sendall('无效的命令'.encode('utf-8'))

    client_socket.close()
